<?php

namespace app\admin\controller\vactivities;

use app\admin\model\vactivities\Ticket;
use app\common\controller\Backend;
use app\common\library\Iden;
use Exception;
use think\Config;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 系列活动管理
 *
 * @icon fa fa-circle-o
 */
class Seriesactivity extends Backend
{
    
    /**
     * Seriesactivity模型对象
     * @var \app\admin\model\vactivities\Seriesactivity
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vactivities\Seriesactivity;
        $catemodel = new \app\admin\model\superdata\Activitycategory;
        $tagsmodel = new \app\admin\model\superdata\Activitytags;
        $this->view->assign('categoryList',$catemodel->getCategoryList());
        $this->view->assign('AtagsList',$tagsmodel->getAtagsList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        $mywhere['admin_id'] = $this->auth->id;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where($mywhere)
                ->order($sort, $order)
                ->paginate($limit);

            $tagsmodel = new  \app\admin\model\superdata\Activitytags;
            $catemodel = new  \app\admin\model\superdata\Activitycategory;
            foreach ($list as $row) {
                $row['tags'] = $tagsmodel->getTagsNameById($row['tags']);
                $row['category'] = $catemodel->getcateNameById($row['category']);
            }
           $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        //$this->assignconfig('pack_id',$pack_id);
        return $this->view->fetch();
    }



    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['admin_id'] = $this->auth->id;
            $params['serial'] = nonceStr();
            $tmodel = new \app\admin\model\vactivities\Ticket;
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }


                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $count = count(array_filter($params['ticket_name']));
                    if($count == 0){
                        $count = count(array_filter($params['ticket_price']));
                    }
                    if($count > 0){//添加入场卷
                        for($i = 0;$i < $count;$i++){
                            if($params['ticket_price'][$i]==0 || $params['ticket_price'][$i]==0.00){
                                $params['ticket_name'][$i] = 'VIP入场券';
                            }
                            $t[] = [
                                'name'=>$params['ticket_name'][$i],
                                'price'=>priceyuantofen($params['ticket_price'][$i]),
                                'number'=>$params['ticket_number'][$i],
                                'activity_id'=>$this->model->id,
                                'type'=>Ticket::TICKET_TYPE_1,
                                'admin_id'=>$this->auth->id,
                                'createTime' => date('Y-m-d H:i:s',time())
                            ];

                        }
                        $count = count(array_filter($t));
                        if($count > 0 ){
                            $tmodel->insetAll($t);
                        }
                    }
                    Db::commit();

                    unset($t);
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        $tmodel = new \app\admin\model\vactivities\Ticket;
        $tlist = $tmodel->getTicketList($ids,Ticket::TICKET_TYPE_1,'');
        $row['tlist'] = isset($tlist) ? json_encode($tlist, JSON_UNESCAPED_UNICODE) : '';
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    $tArr = $tmodel->getTicketByActId($params['id'],Ticket::TICKET_TYPE_2);//查找活动下的入场卷
                    $tnArr = [];
                    if(!empty($params['ticket_name']) || !empty($params['ticket_price'])){//添加入场卷
                        $count = count($params['ticket_name']);
                        if($count == 0){
                            $count = count($params['ticket_price']);
                        }
                        for($i = 0;$i < $count;$i++){
                            if($params['ticket_price'][$i]==0 || $params['ticket_price'][$i]==0.00){
                                $params['ticket_name'][$i] = 'VIP入场券';
                            }

                            if(!empty($params['ticket_id'][$i])){//获取到入场卷id则更新
                                $rs = $tmodel->findId($params['ticket_id'][$i]);
                                if($rs){
                                    $u[]=[
                                        'id' =>$params['ticket_id'][$i],
                                        'price'=>priceyuantofen($params['ticket_price'][$i]),
                                        'name'=>$params['ticket_name'][$i],
                                        'number'=>$params['ticket_number'][$i],
                                        'activity_id'=>$params['id'],
                                        'type'=>Ticket::TICKET_TYPE_1,
                                        'admin_id'=>$this->auth->id,
                                        'updateTime' => date('Y-m-d H:i:s',time())
                                    ];
                                    $tnArr[] = $params['ticket_id'][$i];//只获取查找到的入场卷id
                                }
                            }else{
                                $t[] = [
                                    'name'=>$params['ticket_name'][$i],
                                    'price'=>priceyuantofen($params['ticket_price'][$i]),
                                    'number'=>$params['ticket_number'][$i],
                                    'activity_id'=>$params['id'],
                                    'type'=>Ticket::TICKET_TYPE_1,
                                    'admin_id'=>$this->auth->id,
                                    'createTime' => date('Y-m-d H:i:s',time())
                                ];
                            }
                        }

                        if(isset($t)){//批量插入
                            $tmodel->insetAll($t);
                        }
                        if(isset($u)){//批量更新
                            $tmodel->updataAll($u);
                        }
                    }

                    if(!empty($tArr)){//查找俩数组中不同元素
                        $tmodel->delAll($tArr,$tnArr);
                    }
                    Db::commit();
                    unset($u);
                    unset($t);
                    unset($tArr);
                    unset($tnArr);
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail()
    {
        $ids = $this->request->param("ids");
        $state = input('status/d');
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if(is_array($adminIds)){
            if (!in_array($row[$this->dataLimitField],$adminIds)){
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isAjax()) {
            if ($state == 1){
                $state = 0;
            }else {
                $state = 1;
            }

//            else if ($state ==99){
//                $this->error(__('You have no permission'));
//                return false;
//            }

            Db::name('series_activity')->where('id',$ids)->update(['status'=>$state]);

            $this->success("Ajax请求成功", null, ['id' => $ids]);
        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }
    public function tagslist(){
        $tagsmodel = new \app\admin\model\superdata\Activitytags;
        return json(['list' => $tagsmodel->getTagsList()]);
    }


}
